<template>
  <div class="app-container">
    <el-table :data="list" border style="width: 100%" max-height="450px" @cell-dblclick="updata">
      <el-table-column type="index" label="#" width="50"></el-table-column>
      <el-table-column prop="name" label="类别名称" width="850">
        <template slot-scope="scope">
          <el-input
            @change="saveFn(scope.row)"
            class="inp"
            v-focus
            v-if="scope.row.bool"
            v-model="scope.row.name"
          ></el-input>
          <el-tag v-else type="primary" disable-transitions>{{scope.row.name}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column class="cells" label="操作">
        <template slot-scope="scope">
          <el-button v-show="scope.$index == 0" type="primary" class="baocun">增加</el-button>
          <el-button v-show="!scope.$index == 0" @click="updata(scope.row)" type="warning">修改</el-button>
          <el-button v-show="!scope.$index == 0" @click="removeFn(scope.row)" type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { mapActions } from "vuex";
export default {
  data() {
    return {
      visible: false,
      form: {},
      isShowhide: false
    };
  },
  directives: {
    //自定义属性获取焦点
    focus: {
      inserted(el) {
        el.getElementsByTagName("input")[0].focus();
      }
    }
  },
  mounted() {
    this.getListFun();
  },
  methods: {
    ...mapActions("classify", [
      "getListFun",
      "addListFun",
      "updateListFun",
      "deleteListFun"
    ]),
    updata(row) {
      row.bool = true;
    },
    //删除
    removeFn(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          await this.deleteListFun(row.id);
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          await this.getListFun();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //新增or修改
    async saveFn(res) {
      if (res.id) {
        await this.updateListFun(res);
      } else {
        await this.addListFun(res);
      }
      this.$message({
        type: "success",
        message: `操作成功!`
      });
      await this.getListFun();
    }
  },
  computed: {
    list() {
      let res = this.$store.state.classify.list.map(item => {
        return (item = { ...item, bool: false });
      });
      res.unshift({
        name: "",
        bool: true
      });
      return res;
    }
  }
};
</script>

<style scoped>
.baocun {
  margin-left: 10px;
}
</style>